package com.sky.service.impl;

//import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.sky.context.BaseContext;
import com.sky.dto.ShoppingCartDTO;
import com.sky.entity.Dish;
import com.sky.entity.Setmeal;
import com.sky.entity.ShoppingCart;
import com.sky.mapper.DishMapper;
import com.sky.mapper.SetmealMapper;
import com.sky.mapper.ShoppingCartMapper;
import com.sky.service.ShoppingCartService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

/**
 * @author 李志红
 */
@Service
public class ShoppingCartServiceImpl  implements ShoppingCartService {

    @Autowired
    private ShoppingCartMapper shoppingCartMapper;

    @Autowired
    private DishMapper dishMapper;

    @Autowired
    private SetmealMapper setmealMapper;



    /**
     * 添加购物车
     * @param dto 请求类
     */
    @Override
    public ShoppingCart addCart(ShoppingCartDTO dto) {
        ShoppingCart cart = new ShoppingCart();
        BeanUtils.copyProperties(dto,cart);
        cart.setUserId(BaseContext.getCurrentId());

        List<ShoppingCart> list = shoppingCartMapper.findAll(dto);
        System.out.println(list);

        if (list !=null && list.size() == 1) {
             cart = list.get(0);
            cart.setNumber(cart.getNumber()+1);
            shoppingCartMapper.updateById(cart);
        }else {

            Long dishId = dto.getDishId();
            if (dishId != null){
                Dish dish = dishMapper.getDishById(dishId);
                cart.setName(dish.getName());
                cart.setImage(dish.getImage());
                cart.setAmount(dish.getPrice());

            }else {
                //添加到购物车的是套餐
                Long setmealId = dto.getSetmealId();
                if (setmealId != null){
                    Setmeal setmeal = setmealMapper.getSetmealById(setmealId);
                    cart.setName(setmeal.getName());
                    cart.setImage(setmeal.getImage());
                    cart.setAmount(setmeal.getPrice());
                }

            }
            cart.setNumber(1);
            cart.setCreateTime(LocalDateTime.now());
            shoppingCartMapper.addCart(cart);
        }

        return cart;

    }

    /**
     * 清空购物车
     */
    @Override
    public void clearShoppingCart() {
        Long userId = BaseContext.getCurrentId();
        shoppingCartMapper.deleteByUserId(userId);
    }

    /**
     * 查询购物车
     * @return 查询结果
     */
    @Override
    public List<ShoppingCart> getAll() {
        Long userId = BaseContext.getCurrentId();
        return shoppingCartMapper.getAllCarts(userId);
    }


}
